﻿using DNFImagePacks2Manager.Helpers;
using Microsoft.UI.Xaml.Controls;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

namespace DNFImagePacks2Manager.Models
{
    public class BKItemCustom(string filename) : BKItemBase(Path.GetFileNameWithoutExtension(filename), "配置")
    {
        public string Suffix { get; set; } = Path.GetExtension(filename);
        public string FileName { get; set; } = filename;
        public string CsmFile => Path.Combine(BKHelper.GetCustomFolder(), FileName);


        public Dictionary<string, BKItemHash> ReadCsmFile()
        {
            Dictionary<string, BKItemHash> dic = [];
            string file = CsmFile;
            if (File.Exists(file))
            {
                try
                {
                    string json = File.ReadAllText(file);
                    var items = JsonConvert.DeserializeObject<Dictionary<string, BKItemHash>>(json);
                    if (items != null)
                    {
                        return items;
                    }
                }
                catch (Exception)
                {
                }
            }
            return dic;
        }

        public override void Apply(Page page)
        {
            if (!LocalStorageHelper.IsSetDNFPath())
            {
                DialogHelper.ShowErrorMessage(page, "应用失败: 未设置DNF路径");
                return;
            }

            string file = CsmFile;
            if (File.Exists(file))
            {
                try
                {
                    var items = ReadCsmFile();
                    if (items.Count == 0)
                    {
                        DialogHelper.ShowErrorMessage(page, "应用失败: 读取文件失败");
                        return;
                    }
                    string bkPath = LocalStorageHelper.GetBKOfficialPath();
                    string storagePath = LocalStorageHelper.GetBKStoragePath();
                    int success = 0;
                    List<string> fails = [];
                    int totalFile = items.Count;
                    foreach (var item in items)
                    {
                        string relativePath = item.Key;
                        string path = item.Value.GetAbsoluteFile(storagePath);
                        string targetPath = Path.Combine(bkPath, relativePath);
                        try
                        {
                            if (File.Exists(targetPath))
                            {
                                File.Delete(targetPath);
                            }
                            File.Copy(path, targetPath);
                            success++;
                        }
                        catch (Exception)
                        {
                            fails.Add(relativePath);
                        }
                    }
                    if (fails.Count == 0)
                    {
                        DialogHelper.ShowSuccessMessage(page, $"成功，应用 {success} 个文件");
                    }
                    else
                    {
                        ListView listView = new()
                        {
                            ItemsSource = fails
                        };

                        DialogHelper.ShowNormalDialog(page, $"{fails.Count} 个文件应用失败", listView);
                    }
                }
                catch (Exception)
                {
                    DialogHelper.ShowErrorMessage(page, "应用失败: 读取文件失败");
                }
            }
            else
            {
                DialogHelper.ShowErrorMessage(page, "应用失败: 找不到文件");
            }
        }

        public override bool Delete(Page page)
        {
            try
            {
                string file = CsmFile;
                if (File.Exists(file))
                {
                    File.Delete(file);
                }
                DialogHelper.ShowSuccessMessage(page, "删除成功");
                return true;
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"删除失败: {ex.Message}");
                return false;
            }
        }

        public override bool Rename(Page page, string name)
        {
            try
            {
                string file = CsmFile;
                string newFileName = name + Suffix;
                string newFile = Path.Combine(BKHelper.GetCustomFolder(), newFileName);
                if (File.Exists(file))
                {
                    if (File.Exists(newFile))
                    {
                        DialogHelper.ShowErrorMessage(page, "重命名失败: 目标文件已存在");
                    }
                    else
                    {
                        File.Move(file, newFile);
                        FileName = newFileName;
                        Name = name;
                        DialogHelper.ShowSuccessMessage(page, "重命名完成");
                        return true;
                    }
                }
                else
                {
                    DialogHelper.ShowErrorMessage(page, "重命名失败: 找不到文件");
                }
            }
            catch (Exception ex)
            {
                DialogHelper.ShowErrorMessage(page, $"重命名失败: {ex.Message}");
            }
            return false;
        }

        public override void Preview(Page page)
        {
            string file = CsmFile;
            if (File.Exists(file))
            {
                try
                {
                    var items = ReadCsmFile();
                    if (items.Count == 0)
                    {
                        DialogHelper.ShowErrorMessage(page, "预览失败: 读取文件失败");
                        return;
                    }
                    var categories = BKPathHelper.CategoryDirectory;
                    List<string> nameList = [];
                    foreach (var item in items)
                    {
                        string path = item.Key;
                        string targetName = item.Value.name;
                        string mapName = categories.GetValueOrDefault(path, path);
                        nameList.Add($"{mapName}: {targetName}");
                    }

                    ListView listView = new()
                    {
                        ItemsSource = nameList
                    };

                    DialogHelper.ShowNormalDialog(page, $"{Name} ({nameList.Count})", listView);
                }
                catch (Exception)
                {
                    DialogHelper.ShowErrorMessage(page, "预览失败: 读取文件失败");
                }
            }
            else
            {
                DialogHelper.ShowErrorMessage(page, "预览失败: 找不到文件");
            }
        }

        public override void Edit(Page page)
        {
            string file = CsmFile;
            if (File.Exists(file))
            {
                ConsoleHelper.OpenFileInNotepad(file);
            }
            else
            {
                DialogHelper.ShowErrorMessage(page, "编辑失败: 找不到文件");
            }
        }

        public override void Export(Page page)
        {
            string file = CsmFile;
            if (File.Exists(file))
            {
                try
                {
                    var items = ReadCsmFile();
                    if (items.Count == 0)
                    {
                        DialogHelper.ShowErrorMessage(page, "导出失败: 读取文件失败");
                        return;
                    }

                    string storagePath = LocalStorageHelper.GetBKStoragePath();
                    string rootFolder = "Video";
                    Dictionary<string, string> compressFiles = [];

                    foreach (var item in items)
                    {
                        string targetPath = Path.Combine(rootFolder, item.Key);
                        string filePath = item.Value.GetAbsoluteFile(storagePath);
                        compressFiles.Add(targetPath, filePath);
                    }


                    DialogHelper.ShowSavePickerAndExportZip(page, Name, compressFiles);
                }
                catch (Exception)
                {
                    DialogHelper.ShowErrorMessage(page, "导出失败: 读取文件失败");
                }
            }
            else
            {
                DialogHelper.ShowErrorMessage(page, "导出失败: 找不到文件");
            }
        }
    }
}